package com.ledim.ledimview;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.ledim.bean.base.BaseListResponse;
import com.ledim.adapter.SearchSuggestedAdapter;
import com.ledim.bean.LedimSearchSuggestion;
import com.ledim.itf.LedimOnItemClickListener;
import com.ledim.itf.LedimSearchInterface;
import com.ledim.service.LedimHttpObserver;
import com.letv.android.young.client.R;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.ClearEditText;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchBarView extends LinearLayout
        implements LedimOnItemClickListener<LedimSearchSuggestion> {

    private ClearEditText mSearchKey;
    private String mKeyTemp = "";
    private Context mContext;
    private String mKey;
    private SearchSuggestedAdapter mAdapter;
    private ListView mListViewSuggested;
    private ArrayList<LedimSearchSuggestion> subList = new ArrayList<LedimSearchSuggestion>();
    private LedimSearchInterface mSeachInterface;

    public SearchBarView(Context context) {
        super(context);
        mContext = context;
    }

    public SearchBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public SearchBarView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //        init();
    }

    public void bindData(String key, LedimSearchInterface seachInterface) {
        mSeachInterface = seachInterface;
        mKey = key;
        init();
    }

    /**
     * 初始化界面
     */
    private void init() {
        mSearchKey = (ClearEditText) findViewById(R.id.search_keyword);
        mListViewSuggested = (ListView) findViewById(R.id.listView_searches);
        mListViewSuggested.setVisibility(View.GONE);
        if (mKey != null) {
            mSearchKey.setText(mKey);
            mSearchKey.setSelection(mKey.length());
        } else {
            mSearchKey.setText("");
        }
        //联想搜索
        mSearchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mKeyTemp = mSearchKey.getText().toString().trim();
                if (mSearchKey.getFlag()) {
                    if (!TextUtils.isEmpty(mKeyTemp)) {
                        getSearchSug(mKeyTemp);
                    } else {
                        mSeachInterface.notifyViewVisible(VISIBLE);
                        mListViewSuggested.setVisibility(View.GONE);
                    }
                }
            }
        });
        //搜索
        mSearchKey.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearchKeyword();
                    return true;
                }
                return false;
            }

        });
        if (mSeachInterface != null && mSeachInterface.autoShowKeyBoard()) {
            openKeyBoard();
        }
        mListViewSuggested.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                closeKeyBoard();
                return true;
            }
        });

    }

    /**
     * @param s
     *         获取sug数据
     */
    private void getSearchSug(String s) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .getSearchSuggestion(s)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseListResponse<LedimSearchSuggestion>>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     e.printStackTrace();
                                 }

                                 @Override
                                 public void onNext(BaseListResponse<LedimSearchSuggestion> data) {
                                     super.onNext(data);
                                     if (data != null && data.success) {
                                         mListViewSuggested.setVisibility(View.VISIBLE);
                                         mSeachInterface.notifyViewVisible(GONE);
                                         if (!mKeyTemp.equals("") && data.data != null) {
                                             if (mAdapter == null) {
                                                 mAdapter =
                                                         new SearchSuggestedAdapter(mContext, SearchBarView.this, mKeyTemp);
                                                 mListViewSuggested.setAdapter(mAdapter);
                                             } else {
                                                 mAdapter.setKeyTemp(mKeyTemp);
                                             }
                                             if (data.data.size() == 0) {
                                                 mAdapter.setDatas(data.data);
                                             } else {
                                                 subList.clear();
                                                 if (data.data.size() > 10) {
                                                     subList.addAll(data.data.subList(0, 10));
                                                 } else {
                                                     subList.addAll(data.data);
                                                 }

                                                 mAdapter.setDatas(subList);
                                             }
                                         }
                                     }
                                 }
                             });
    }

    public void setSearchKey(String key) {
        mSearchKey.setFlag(false);//EditText改变文字，
        mSearchKey.setText(key);
        mSearchKey.setSelection(key.length());
        mSearchKey.setFlag(true);
        mListViewSuggested.setVisibility(View.GONE);

    }

    public void setListViewSuggestedGone() {
        mListViewSuggested.setVisibility(View.GONE);
    }

    /**
     * 执行搜索操作
     */
    private void doSearchKeyword() {
        if (mSearchKey.getText().toString().trim().equals("")) {
            ToastUtil.toast("请输入搜索内容");
        } else {
            if (mSeachInterface != null) {
                mSeachInterface.doSearch(mSearchKey.getText().toString());
            }
        }
    }

    /**
     * 打开键盘
     */
    private void openKeyBoard() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager = (InputMethodManager) mSearchKey.getContext()
                                                                                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(mSearchKey, 0);
                           }
                       },

                200);
    }

    /**
     * 关闭键盘
     */
    public void closeKeyBoard() {
        mSearchKey.clearFocus();
        InputMethodManager imm =
                (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mSearchKey.getWindowToken(), 0);
    }

    @Override
    public void onItemClick(int position, LedimSearchSuggestion item, View v) {
        if (mSeachInterface != null) {
            mSeachInterface.doSearch(item.name);
        }
    }
}
